const path = require('path')
const fs = require('fs')

function getFilesChildren(paths, toPath) {
  const items = fs.readdirSync(paths);
  const resultMD = [];
  items.forEach(item => {
    if(path.extname(item) === '.md') {
      let title = item;
      const md = paths + '/' + item;
      const data = fs.readFileSync(md, 'utf8')
      const arr = data.split('\n');
      arr.forEach(fe => {
        const reg = /(^#)\s/g;
        const titleArr = fe.match(reg);
        if(titleArr) title = fe.slice(2, fe.length);
      });

      const names = item.slice(0, item.lastIndexOf('.'));

      const filePath = './docs/' + toPath + '/' + names + '.md';
      if (!fs.existsSync(filePath)) {
        mkdir(filePath);
      }
      fs.writeFileSync(filePath, fs.readFileSync(paths + '/' + item));

      resultMD.push({ text: title, link: '/' + toPath + '/' + names })
    }
  });
  return resultMD;
}

function getFilesAndFoldersInDir(paths, toPath) {
  const items = fs.readdirSync(paths);
  const resultMD = [];
  items.forEach(item => {
    const itemPath = `${paths}/${item}`;
    const stat = fs.statSync(itemPath);
    if (stat.isDirectory()) {
      let data = {
        // 文件夹
        type: 'folder',
        name: item
      }
      let children = getFilesAndFoldersInDir(itemPath, toPath)
      if (children && children.length) {
        data.children = children
      }
      resultMD.push(data);
    } else {
      if(path.extname(item) === '.md') {
        let title = item;
        const md = paths + '/' + item;
        const data = fs.readFileSync(md, 'utf8')
        const arr = data.split('\n');
        arr.forEach(fe => {
          const reg = /(^#)\s/g;
          const titleArr = fe.match(reg);
          if(titleArr) title = fe.slice(2, fe.length);
        });

        const names = paths.slice(paths.lastIndexOf('/') + 1, paths.length);
        const filePath = './docs/' + toPath + '/' + names + '.md';
        if (!fs.existsSync(filePath)) {
          mkdir(filePath);
        }
        fs.writeFileSync(filePath, fs.readFileSync(paths + '/' + item));

        resultMD.push({ type: 'file', name: names, title: title });
      }
    }
  });
  return resultMD;
}

function mkdir(filePath) {
  const dirCache = {};
  const arr = filePath.split('/');
  let dir = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (!dirCache[dir] && !fs.existsSync(dir)) {
      dirCache[dir] = true;
      fs.mkdirSync(dir);
    }
    dir = dir + '/' + arr[i];
  }
  fs.writeFileSync(filePath, '')
}

function getCompChildren(fileUrl, toPath) {
  let list = getFilesAndFoldersInDir(fileUrl, toPath)
  // console.log(list);
  list = list.filter(f => f.type === 'folder').map(m => m.children || []).flat().filter(f => f.type === 'file')
  
  const children = [];
  list.forEach(folder => {
    children.push({ text: folder.title, link: '/' + toPath + '/' + folder.name })
  })
  return children;
}

const dataComp = getCompChildren('./packages/components', 'components')
const dataDire = getCompChildren('./packages/directive', 'directive')
const dataServ = getCompChildren('./packages/service', 'service')
const dataHooks = getFilesChildren('./packages/hooks', 'hooks')
const dataGuide = getFilesChildren('./docs/guide', 'guide')
const content = `module.exports = {
  '/guide/': ${JSON.stringify(dataGuide)},
  '/components/': ${JSON.stringify(dataComp)},
  '/directive/': ${JSON.stringify(dataDire)},
  '/service/': ${JSON.stringify(dataServ)},
  '/hooks/': ${JSON.stringify(dataHooks)},
}`
fs.writeFile('./docs/components/sidebar.js', content, err => {
  if (err) {
  	console.error(err);
  }
	// file written successfully
});

